#! /usr/bin/env ruby
#
# This file is part of uhferret, providing a web service interface.
#
# Author::    Peter Lane
# Copyright:: Copyright 2012, Peter Lane.
# License::   GPLv3
#
# uhferret is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# uhferret is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with uhferret.  If not, see <http://www.gnu.org/licenses/>.

require "optparse"
require "webferret"

# Name of the ferret software
FERRET = "uhferret"
# Base folder for working with files
$base = "#{Dir.pwd}/FerretFiles/"
# Port number for server
port = 2000

options = OptionParser.new do |opts|
  opts.banner = "Usage: uhferret-server [options]"
  opts.on("-h", "--help", "help message") do |v|
    puts options
    exit!
  end
  # -- port number
  opts.on("-p", "--port n", Integer, "port number") do |v|
    port = v
  end
  # -- base folder
  opts.on("-f", "--folder FOLDER", "base folder") do |v|
    $base = File.expand_path v
  end
end

begin
  options.parse!

  # Refuse to work if the folder already exists
  if File.exists? $base
    puts "Folder #{$base} already exists"
    puts "Please empty the folder before starting the ferret server"
    exit!
  end

  # install the ferret server at given Port number
  ferret = HTTPServer.new(:Port => port, :DocumentRoot => "/")

  ferret.mount "/ferret/home", UHFerret::FerretHomeServlet
  ferret.mount "/ferret/report", UHFerret::FerretReportServlet

  trap("INT") { ferret.shutdown }

  ferret.start
end

